import 'package:aweb5/bean/aplus/material_type_entity.dart';
import 'package:aweb5/util/DialogUtil.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:aweb5/custom/pull_torefresh.dart';
import 'package:aweb5/bean/aplus/material_list_entity.dart';
import 'package:aweb5/generated/json/material_list_entity_helper.dart';
import 'package:aweb5/generated/json/material_type_entity_helper.dart';
import 'package:load/load.dart';
import 'package:aweb5/Constants.dart';
import 'package:aweb5/config/Config.dart';
import 'package:aweb5/util/toast_util.dart';
import 'package:aweb5/util/HttpClient.dart';
import 'package:aweb5/util/NaviUtil.dart';
import 'package:aweb5/pages/fromlib_plan_detail.dart';
import 'package:progress_dialog/progress_dialog.dart';
import 'package:aweb5/widgetlib/LoadingDialog1.dart';
//import 'package:flutter_easyloading/flutter_easyloading.dart';
class PubMaterial extends StatefulWidget {
//  PubMaterial(this.materialListEntity,this.materialTypeEntity,this.load,this.refresh);

  String search = "";
  GlobalKey<PubMaterialState> key;
//  MyMaterial(this.search,this.key):super(key:key);
  PubMaterial(this.search,this.key):super(key:key);
  @override
  PubMaterialState createState() => PubMaterialState();
}

class PubMaterialState extends State<PubMaterial> with AutomaticKeepAliveClientMixin{
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

//  MaterialListEntity materialListEntity;
  MaterialTypeEntity materialTypeEntity;
//  Function load;
//  Function refresh;

  bool catefinish = false;
  bool materialfinish = false;


  List<MaterialListDataData> data;

  String typeId ="";

  bool get wantKeepAlive => true;

//  ProgressDialog progressDialog;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
//    progressDialog = ProgressDialog(context,type: ProgressDialogType.Normal, isDismissible: true, showLogs: true);
    data = List();
//    requestMaterialType();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      requestMaterial(false);
    });

//    requestMaterial(false);
  }

  void request(){
//    requestMaterialType();
//    requestMaterial(false);
  }
BuildContext _context;
  @override
  Widget build(BuildContext context) {

    this._context = context;
    return b12();
  }

  String materialTypeImg = "";
  Widget b12() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            "素材分类",
            style: b(),
          ),
          SizedBox(
            height: ScreenUtil().setHeight(20),
          ),
          cate(),
          SizedBox(
            height: ScreenUtil().setHeight(18),
          ),
          Expanded(
              child: PullToRefresh().buildRefresh(
                  refresh: this.refresh,
                  load: this.load,
                  child: CustomScrollView(
                    slivers: <Widget>[
//                      SliverToBoxAdapter(
//                        child: Container(
//                          child: Text(
//                            "搜索结果",
//                            style: b(),
//                          ),
//                          margin: EdgeInsets.only(bottom: ScreenUtil().setHeight(20)),
//                        ),
//                      ),
//                      SliverGrid(
//                        delegate: SliverChildBuilderDelegate(
//                              (BuildContext context, int index) {
//                            return Column(
//                              children: <Widget>[
//                                Image.asset(
//                                  "assets/ab.png",
//                                  width: ScreenUtil().setWidth(55),
//                                  height: ScreenUtil().setHeight(55),
//                                ),
//                                SizedBox(
//                                  height: ScreenUtil().setHeight(6),
//                                ),
//                                Text("四川青群扇贝肉加量加大包",
//                                    style: b1(),
//                                    maxLines: 2,
//                                    overflow: TextOverflow.ellipsis,
//                                    textAlign: TextAlign.center),
//                                SizedBox(
//                                  height: ScreenUtil().setHeight(6),
//                                ),
//                                Text(
//                                  "7.22 15:37",
//                                  style: grey(),
//                                ),
//                                SizedBox(
//                                  height: ScreenUtil().setHeight(6),
//                                ),
//                                Row(
//                                  children: <Widget>[
//                                    Text(
//                                      "7.22 15:37",
//                                      style: grey(),
//                                    ),
//                                    SizedBox(
//                                      width: ScreenUtil().setWidth(6),
//                                    ),
//                                    Text(
//                                      "已上架",
//                                      style: TextStyle(
//                                          color: Color(0xffF44336),
//                                          fontSize: ScreenUtil().setSp(12)),
//                                    )
//                                  ],
//                                )
//                              ],
//                            );
//                          },
//                          childCount: 10,
//                        ),
//                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
//                          mainAxisSpacing: 10, // 主轴间距
//                          crossAxisSpacing: 10, // 纵轴间距
//                          crossAxisCount: 3, // 纵轴子元素个数
//                          childAspectRatio: 0.7,
//                        ),
//                      ),
                      SliverToBoxAdapter(
                        child: Container(
                          child: Text(
                            "任务包",
                            style: b(),
                          ),
                          margin: EdgeInsets.only(
                              bottom: ScreenUtil().setHeight(20)),
                        ),
                      ),
                      SliverGrid(
                        delegate: SliverChildBuilderDelegate(
                          (BuildContext context, int index) {
                            return
                              GestureDetector(


                                child:

                                Column(
                                  children: <Widget>[
                                    materialTypeImg.isEmpty?
                                    Image.asset(
                                      "assets/assist/wenjian1.png",
                                      width: ScreenUtil().setWidth(55),
                                      height: ScreenUtil().setHeight(55),
                                    ):Image.network(materialTypeImg,width: ScreenUtil().setWidth(55),
                                        height: ScreenUtil().setHeight(55)),
                                    SizedBox(
                                      height: ScreenUtil().setHeight(6),
                                    ),
                                    Text(
                                      "${data[index].name}",
                                      style: b1(),
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      textAlign: TextAlign.center,
                                    ),
                                    SizedBox(
                                      height: ScreenUtil().setHeight(6),
                                    ),
//                                Text(
//                                  "7.22 15:37",
//                                  style: grey(),
//                                ),
                                    SizedBox(
                                      height: ScreenUtil().setHeight(6),
                                    ),
                                    Row(
                                      children: <Widget>[
//                                    Text(
//                                      "7.22 15:37",
//                                      style: grey(),
//                                    ),
                                        SizedBox(
                                          width: ScreenUtil().setWidth(6),
                                        ),
//                                        Text(
//                                          check(data[index].authStatus),
//                                          style: TextStyle(
//                                              color: Color(0xff00C91E),
//                                              fontSize: ScreenUtil().setSp(12)),
//                                        )
                                      ],
                                    )
                                  ],
                                )

                                ,onTap: (){

                                  if(data[index].authStatus==1)
                                  NaviUtil.push(context, FromLibPlanDetail(null, data[index].name,sendId: data[index].id.toString(),edittable: false,));


                                },

                              )

                              ;
                          },
                          childCount: data.length,
                        ),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          mainAxisSpacing: 1, // 主轴间距
                          crossAxisSpacing: 1, // 纵轴间距
                          crossAxisCount: 3, // 纵轴子元素个数
                          childAspectRatio: 1,
                        ),
                      ),
                    ],
                  ),
                  pulldown: false,
                  pullup: true,
                  refreshController: refreshController))
        ],
      ),
    );
  }
  String check(int status){

    if(status==1){
      return "审核通过";
    }
    else if(status==2){
      return "审核不通过";
    }
    else if(status==0){
      return "待审核";
    }else{
      return "";
    }

  }
  Widget cate() {
    return Container(
      height: ScreenUtil().setHeight(80),
      width: ScreenUtil().setWidth(414),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemBuilder: (con, index) {
          return
            GestureDetector(

              child: Container(
                margin: EdgeInsets.only(right: ScreenUtil().setWidth(27)),
                child: Column(
                  children: <Widget>[
                    Image.network(
                      materialTypeEntity.data[index].imgUrl,
                      width: ScreenUtil().setWidth(48),
                      height: ScreenUtil().setHeight(48),
                    ),
                    SizedBox(
                      height: ScreenUtil().setHeight(10),
                    ),
                    Text(
                      "${materialTypeEntity.data[index].name}",
                      style: b1(),
                    )
                  ],
                ),
              ),
              onTap: (){

               materialTypeImg =  materialTypeEntity.data[index].imgUrl;
               typeId = materialTypeEntity.data[index].id.toString();
               requestMaterial(false);

              },

            )
            ;
        },
        itemCount:
            materialTypeEntity == null ? 0 : materialTypeEntity.data.length,
      ),
    );
  }

  void load() {
    currentPage++;
    requestMaterial(true);
  }
  void setSearchWord(String search){
    widget.search =search;
  }
  void refresh() {}

  TextStyle b() {
    return TextStyle(
        color: Color(0xff101010),
        fontSize: ScreenUtil().setSp(16),
        fontWeight: FontWeight.bold);
  }

  TextStyle b1() {
    return TextStyle(
        color: Color(0xff101010), fontSize: ScreenUtil().setSp(14));
  }

  TextStyle grey() {
    return TextStyle(
        color: Color(0xffa7a7a7), fontSize: ScreenUtil().setSp(14));
  }
//素材
  int currentPage = 1;
  void requestMaterial(bool load) async {
//    EasyLoading.showSuccess("正在加载……");
    print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>pub");
//    var v = await showLoadingDialog();
//    await progressDialog.show();

//    NaviUtil.push(context, LoadingDialog1(false));

    DialogUtil.showloadingdialog(this._context);
    try {
      print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>pub1");
      Map<String, dynamic> map = Map<String, dynamic>();

      map["member_id"] = "";
      map["type_id"] = typeId;
      map["keyword"] = widget.search;
      map["page"] = currentPage;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + 'light/task/index',
          data: map);
      print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>pub${map1.toString()}");
//      progressDialog.hide();
      MaterialListEntity loginEntity = new MaterialListEntity();

      loginEntity = materialListEntityFromJson(loginEntity, map1);

      DialogUtil.pop(this._context);
      requestMaterialType();
      if (loginEntity.code == null || loginEntity.code != 200) {
//        Fluttertoast.showToast(msg: "null");
        Toast.show(msg: loginEntity.msg);
//        v.dismiss();
        return;
      }
      if (loginEntity.code == 200) {
//        Toast.show(msg: "创建成功");
//        NaviUtil.pop(this.context);

//        v.dismiss();


      if(load){
        if(loginEntity.data.data.length>0){
          data.addAll(loginEntity.data.data);
          refreshController.loadComplete();
        }else{
          refreshController.loadNoData();
        }
      }else{
        data =loginEntity.data.data;
      }


//        materialListEntity = loginEntity;
        setState(() {});
      }
    } catch (e) {
      if(load){
        refreshController.loadFailed();
      }

      DialogUtil.pop(this._context);
//      progressDialog.hide();
      print(e.toString());
      print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>pub${e.toString()}");
//      v.dismiss(true);
    requestMaterialType();
    }
  }

  void requestMaterialType() async {
//     await  progressDialog.show();

//    NaviUtil.push(context, LoadingDialog1(false));

      DialogUtil.showloadingdialog(this._context);
//    EasyLoading.showSuccess("正在加载……");
    try {
      Map<String, dynamic> map = Map<String, dynamic>();

      map["member_id"] = Constants.memberInfoEntity.data.memberId;
      map["type_id"] = typeId;
      map["keyword"] = widget.search;
      map["page"] = currentPage;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + 'light/task/type',
          data: map);

//      progressDialog.hide();
      MaterialTypeEntity loginEntity = new MaterialTypeEntity();

      loginEntity = materialTypeEntityFromJson(loginEntity, map1);

      DialogUtil.pop(this._context);

//      EasyLoading.dismiss();
      if (loginEntity.code == null || loginEntity.code != 200) {
//        Fluttertoast.showToast(msg: "null");
        Toast.show(msg: loginEntity.msg);
         return;
      }
      if (loginEntity.code == 200) {
//        Toast.show(msg: "创建成功");
//        NaviUtil.pop(this.context);


        materialTypeEntity = loginEntity;
        setState(() {

        });
      }
    } catch (e) {
//      progressDialog.hide();

//      NaviUtil.pop(context);

    DialogUtil.pop(this._context);
      print(e.toString());
//      v.dismiss(true);
    }
  }
}
